// const loaderUtils = require('loader-utils')

const defaultOpts = {
  remUnit: 16,
  remFixed: 4
}

// const opts = loaderUtils.getOptions(this)

const config = Object.assign({}, defaultOpts)

const ZPXRegExp = /(?<=(\b|\'|\"|\s|;))(\d+(\.\d+)?)px(?=(\b|\'|\"|\s|;))/
const TEMRegExp = /<template>(.|\n|\r)+<\/template>/

module.exports = function (source) {
  try {
    let pxGlobalRegExp = new RegExp(ZPXRegExp.source, 'g');
    let temGlobalRegExp = new RegExp(TEMRegExp.source, 'g');
    if (this.cacheable) {
      this.cacheable()
    }
    const match = source.match(temGlobalRegExp)
    if (match && match.length && pxGlobalRegExp.test(source)) {
      let template = ''
      template = match[0]
      let others = source.split(template)

      const _template = template.replace(pxGlobalRegExp, ($0, $1) => {
        let num = $0.substring(0, $0.length - 2)
        let val = Number(num) / config.remUnit
        val = parseFloat(val.toFixed(config.remFixed))
        return val === 0 ? val : val + 'rem'
      })
      return others.join(_template)
    } else {
      return source
    }
  } catch {
    return source
  }
}
